﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 基于内存的事件总线
    /// </summary>
    public class MemoryEventBus : IEventBus
    {

        private readonly Dictionary<Type, List<object>> collection;

        /// <summary>
        /// 构建基于内存的事件总线。
        /// </summary>
        public MemoryEventBus()
        {
            this.collection = new Dictionary<Type, List<object>>();
        }

        /// <summary>
        /// 发布事件。
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="channel"></param>
        /// <param name="event"></param>
        public void Publish<TEvent>(string channel, TEvent @event) where TEvent : IEventBase
        {
            if (this.collection.ContainsKey(typeof(TEvent)))
            {
                List<object> eventHandlerCollection = this.collection[typeof(TEvent)];
                foreach (var item in eventHandlerCollection)
                {
                    if (item is IEventHandler<TEvent> handler)
                        handler.Handler(@event);
                }
            }
        }

        /// <summary>
        /// 移除订阅的事件。
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="handler"></param>
        public void RemoveSubscription<TEvent>(IEventHandler<TEvent> handler) where TEvent : IEventBase
        {
            if (this.collection.ContainsKey(typeof(TEvent)))
            {
                List<object> eventHandlerCollection = this.collection[typeof(TEvent)];
                eventHandlerCollection.Remove(handler);
            }
        }

        /// <summary>
        /// 订阅事件。
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        public void Subscribe<TEvent>(string channel, IEventHandler<TEvent> handler) where TEvent : IEventBase
        {
            if (!this.collection.ContainsKey(typeof(TEvent)))
                this.collection.Add(typeof(TEvent), new List<object>());
            List<object> eventHandlerCollection = this.collection[typeof(TEvent)];
            eventHandlerCollection.Add(handler);
        }
    }
}
